from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer,BadData
from mall import settings
from users.models import User


def generic_verify_url(user_id,email):
    # 1.创建序列化器
    serializer = Serializer(secret_key=settings.SECRET_KEY,expires_in=3600)
    data = {
        'user_id':user_id,
        'email':email
    }
    token = serializer.dumps(data)
    return 'http://www.meiduo.site:8080/success_verify_email.html?token=' + token.decode()


def check_verify_email_token(token):
    serializer = Serializer(settings.SECRET_KEY, 3600)
    try:
        # 加载token
        result = serializer.loads(token)
    except BadData:
        return None
    else:
        user_id = result.get('user_id')
        email = result.get('email')
        try:
            user = User.objects.get(id=user_id, email=email)
        except User.DoesNotExist:
            user = None
        else:
            return user